#!/usr/bin/env python3
# -*- coding: utf_8 -*-

import json
import traceback
from bottle import app, request, get, _parse_qsl

from urllib.parse import unquote

import jinja2
import markdown

from mie.bprint import varfmt
from mie.dotdict import DotDict


@get("/_/urls")
def misc_urls():
    routes = app[0].routes
    urls = []
    for r in routes:
        urls.append("%s %s" % (r.method.rjust(7), r.rule))
    return varfmt(urls)


@get("/_/doc")
def misc_doc():
    TEMPLATE = """<!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <link href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.0/css/bootstrap-combined.min.css" rel="stylesheet">
        <style>
            body {
                font-family: sans-serif;
            }
            code, pre {
                font-family: monospace;
            }
            h1 code,
            h2 code,
            h3 code,
            h4 code,
            h5 code,
            h6 code {
                font-size: inherit;
            }
        </style>
    </head>
    <body>
    <div class="container">
    {{content}}
    </div>
    </body>
    </html>
    """

    try:
        md = open("./README.md").read()
    except:
        return "README.md not found"

    extensions = ["extra", "smarty"]
    html = markdown.markdown(md, extensions=extensions, output_format="html5")
    doc = jinja2.Template(TEMPLATE).render(content=html)

    return doc


def body(raw=False, jsonmode=False, encoding="utf-8"):
    if raw:
        return request.body.read()

    try:
        payload = request.body.read() or "{}"
        dic = json.loads(payload.decode(encoding), strict=True)
        if jsonmode:
            return dic
        else:
            dic = DotDict(**dic)
            return dic
    except:
        traceback.print_exc()
        if jsonmode:
            return {}
        else:
            return DotDict()


def paste_fix():
    """convert str to bytes for wsgi_write_chunk()"""
    from paste import httpserver

    wsgi_write_chunk_old = httpserver.WSGIHandlerMixin.wsgi_write_chunk

    def wsgi_write_chunk_new(self, chunk):
        if isinstance(chunk, str):
            chunk = chunk.encode()
        wsgi_write_chunk_old(self, chunk)

    httpserver.WSGIHandlerMixin.wsgi_write_chunk = wsgi_write_chunk_new


def parse_qsl_fix():
    from paste import httpserver

    def parse_qsl(qs):
        r = {}
        for pair in qs.replace(";", "&").split("&"):
            if not pair:
                continue
            nv = pair.split("=", 1)
            if len(nv) != 2:
                nv.append("")
            key = unquote(nv[0].replace("+", " "))
            value = unquote(nv[1].replace("+", " "))
            r[key] = value
        return r
